#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
const std::string PROXY_HOST = "proxy_server_address";
const int PROXY_PORT = 8080;
const std::string TARGET_HOST = "target_server_address";
const int TARGET_PORT = 80;

void httpRequest(const std::string& request) {
    // 创建代理服务器地址结构体
    sockaddr_in proxyAddress{};
    proxyAddress.sin_family = AF_INET;
    proxyAddress.sin_port = htons(PROXY_PORT);
    if (inet_pton(AF_INET, PROXY_HOST.c_str(), &(proxyAddress.sin_addr)) <= 0) {
        std::cerr << "Failed to set proxy address." << std::endl;
        return;
    }

    // 创建目标服务器地址结构体
    sockaddr_in targetAddress{};
    targetAddress.sin_family = AF_INET;
    targetAddress.sin_port = htons(TARGET_PORT);
    if (inet_pton(AF_INET, TARGET_HOST.c_str(), &(targetAddress.sin_addr)) <= 0) {
        std::cerr << "Failed to set target address." << std::endl;
        return;
    }

    // 创建代理服务器Socket
    int proxySocket = socket(AF_INET, SOCK_STREAM, 0);
    if (proxySocket == -1) {
        std::cerr << "Failed to create proxy socket." << std::endl;
        return;
    }

    // 连接代理服务器
    if (connect(proxySocket, (struct sockaddr*)&proxyAddress, sizeof(proxyAddress)) < 0) {
        std::cerr << "Proxy connection failed." << std::endl;
        return;
    }

    // 发送请求至代理服务器
    if (send(proxySocket, request.c_str(), request.length(), 0) < 0) {
        std::cerr << "Failed to send request." << std::endl;
        return;
    }

    // 创建目标服务器Socket
    int targetSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (targetSocket == -1) {
        std::cerr << "Failed to create target socket." << std::endl;
        return;
    }

    // 连接目标服务器
    if (connect(targetSocket, (struct sockaddr*)&targetAddress, sizeof(targetAddress)) < 0) {
        std::cerr << "Target connection failed." << std::endl;
        return;
    }

    // 接收来自代理服务器的响应并将其发送至目标服务器
    char response[4096];
    int bytesRead;
    while ((bytesRead = recv(proxySocket, response, sizeof(response), 0)) > 0) {
        if (send(targetSocket, response, bytesRead, 0) < 0) {
            std::cerr << "Failed to send response to target server." << std::endl;
            return;
        }
    }

    // 接收来自目标服务器的响应并将其发送回客户端
    while ((bytesRead = recv(targetSocket, response, sizeof(response), 0)) > 0) {
        if (send(proxySocket, response, bytesRead, 0) < 0) {
            std::cerr << "Failed to send response to client." << std::endl;
            return;
        }
    }

    // 关闭连接
    close(proxySocket);
    close(targetSocket);
}

